package com.math.aistudykbr.utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;

public class ImagePreprocessor {
    public static BufferedImage preprocess(BufferedImage original) {
        // 1. 转换为灰度图像
        BufferedImage grayImage = toGrayScale(original);

        // 2. 二值化处理
        BufferedImage binaryImage = binarize(grayImage);

        // 3. 降噪处理
        BufferedImage denoisedImage = denoise(binaryImage);

        // 4. 锐化处理
        return sharpen(denoisedImage);
    }

    private static BufferedImage toGrayScale(BufferedImage original) {
        BufferedImage grayImage = new BufferedImage(
                original.getWidth(), original.getHeight(),
                BufferedImage.TYPE_BYTE_GRAY);
        Graphics g = grayImage.getGraphics();
        g.drawImage(original, 0, 0, null);
        g.dispose();
        return grayImage;
    }

    private static BufferedImage binarize(BufferedImage grayImage) {
        BufferedImage binaryImage = new BufferedImage(
                grayImage.getWidth(), grayImage.getHeight(),
                BufferedImage.TYPE_BYTE_BINARY);
        Graphics g = binaryImage.getGraphics();
        g.drawImage(grayImage, 0, 0, null);
        g.dispose();
        return binaryImage;
    }

    private static BufferedImage denoise(BufferedImage image) {
        float[] matrix = {
                1, 1, 1,
                1, 1, 1,
                1, 1, 1
        };
        Kernel kernel = new Kernel(3, 3, matrix);
        ConvolveOp op = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
        return op.filter(image, null);
    }

    private static BufferedImage sharpen(BufferedImage image) {
        float[] sharpenMatrix = {
                0, -1, 0,
                -1, 5, -1,
                0, -1, 0
        };
        Kernel kernel = new Kernel(3, 3, sharpenMatrix);
        ConvolveOp op = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
        return op.filter(image, null);
    }
}